'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //注册
    async registry() {
        //1.接收前端传递的参数,容错处理
        //2.排重
        //3.注册  -- 密码加密  --- 注册
        let {ctx,service} = this;
        let {username,password,num} = ctx.request.body;
        if(username && /\w{4,6}/.test(password) && /\d{11}/.test(num)){
            //2.
            let target = await service.user.selectUser(num);
            if(target.length){
                //已经存在
                ctx.body = {
                    code:4,
                    msg:'此用户已存在'
                }
            }else{
                //密码加密
                let hmcPwd = ctx.helper.hmc(password);
                try{
                    await service.user.registry(username,hmcPwd,num);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //登录
    async login(){
        //1.接收参数,容错
        //2.密码加密，查询  学号和密码一致的
        let {ctx,service} = this;
        let {num,password} = ctx.request.body;
        if(/\d{11}/.test(num) && /\w{4,6}/){
            let hmcPwd = ctx.helper.hmc(password);
            let target = await service.user.login(num,hmcPwd);
            if(target.length){
                let token = jwt.sign({num},'lixd',{expiresIn:60*60*5});
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token,
                    info:{
                        ...target[0]
                    }
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    //获取资源列表
    async resource(){
        //role_id
        let {ctx,service} = this;
        //1.获取role_id  根据role_id查询
        let {role_id} = ctx.query;
        if(role_id){
            let list = await service.user.resource(role_id);
            ctx.body = {
                code:1,
                data:list
            }
        }else{
            ctx.body = {
                code:0,
                msg:'无权限'
            }
        }
    }
}

module.exports = UserController;
